// Global variables
let currentChatId = null;
let currentChatUserId = null;
let allChats = [];
let messageContacts = [];
let currentUserId = null;
let replyToMessageId = null; // ID of message being replied to
let wsConnection = null; // WebSocket connection
let messageHistory = {}; // Store all messages by user ID
let wsInitialized = false; // Flag to prevent multiple WebSocket initialization

// Initialize when document is loaded
document.addEventListener('DOMContentLoaded', function() {
    // Get current user ID
    fetchCurrentUserInfo();
    
    // Initialize event listeners for the new message button
    initializeNewMessageButton();
    
    // Initialize tab switching
    initializeMessageTabs();
    
    // Only load contacts when the messages tab is clicked
    const messagesNavItem = document.querySelector('.nav-item[data-page="messages"]');
    if (messagesNavItem) {
        messagesNavItem.addEventListener('click', function() {
            // Load contacts data when the messages tab is clicked
            loadContactsForMessaging();
        });
    }
    
    // Initialize the send message functionality
    initializeSendMessage();
    
    // Initialize messages page if we're on that page
    if (document.getElementById('messages-page')) {
        initMessagesPage();
    }
});

/**
 * Initialize messages page
 */
function initMessagesPage() {
    // Get current user ID
    currentUserId = getCurrentUserId();
    
    // Load contacts for messaging
    loadContactsForMessaging();
    
    // Setup message input
    setupMessageInput();
    
    // Setup WebSocket for real-time messaging
    setupWebSocket();
    
    // Add development test code in non-production environments
    if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
        // Add test commands to window for console testing
        window.testMessages = {
            simulateIncomingMessage: simulateIncomingMessage,
            showMessageHistory: () => console.log(messageHistory)
        };
        console.log('Message test functions available in console via window.testMessages');
    }
}

/**
 * Simulate an incoming message (for testing)
 * @param {String} fromId Sender ID
 * @param {String} textContent Message content
 */
function simulateIncomingMessage(fromId, textContent) {
    if (!fromId) {
        // If no sender ID provided, use first contact that's not current
        const otherContact = messageContacts.find(c => c.id !== currentUserId && c.id !== currentChatUserId);
        if (otherContact) {
            fromId = otherContact.id;
        } else {
            console.error('No other contacts available for test message');
            return;
        }
    }
    
    const testMessage = {
        type: 'text',
        from: fromId,
        to: currentUserId,
        content: textContent || '这是一条模拟的测试消息 ' + new Date().toLocaleTimeString()
    };
    
    console.log('Simulating incoming message:', testMessage);
    handleWebSocketMessage(testMessage);
}

/**
 * Setup WebSocket for real-time messaging
 */
function setupWebSocket() {
    // Check if WebSocket is already initialized to prevent duplicate message handling
    if (wsInitialized) {
        console.log('WebSocket already initialized, skipping duplicate setup');
        return;
    }
    
    // Initialize WebSocket connection when user info is available
    if (window.wsClient) {
        const userId = getCurrentUserId();
        if (userId) {
            console.log('Setting up WebSocket with user ID:', userId);
            window.wsClient.init(userId.toString());
            
            // Register message handler only once
            window.wsClient.on('message', handleWebSocketMessage);
            wsInitialized = true;
        } else {
            console.log('User ID not available yet, WebSocket setup will happen after user info is fetched');
        }
    } else {
        console.error('WebSocket client not available');
    }
}

/**
 * Fetch current user information from the server
 */
function fetchCurrentUserInfo() {
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/auth/me`, {
        credentials: 'include' // Important to include cookies for authentication
    })
    .then(response => {
        if (!response.ok) {
            console.warn('Could not fetch current user, using default ID');
            window.currentUserId = 1;
            return null;
        }
        return response.json();
    })
    .then(user => {
        if (user && user.id) {
            window.currentUserId = user.id;
            currentUserId = user.id;
            console.log('Messages.js - Current user ID:', currentUserId);
            
            // Initialize WebSocket connection only if not already initialized
            if (window.wsClient && !wsInitialized) {
                window.wsClient.init(user.id.toString());
                
                // Register message handler
                window.wsClient.on('message', handleWebSocketMessage);
                wsInitialized = true;
            } else if (!window.wsClient) {
                console.error('WebSocket client not available');
            }
        }
    })
    .catch(error => {
        console.error('Error fetching current user:', error);
        window.currentUserId = 1;
        currentUserId = 1;
    });
}

/**
 * Handle incoming WebSocket messages
 */
function handleWebSocketMessage(message) {
    console.log('Received WebSocket message:', message);
    
    // Only process messages of type 'text'
    if (message.type === 'text') {
        // Get sender info
        const senderName = getSenderName(message.from);
        const senderAvatar = getSenderAvatar(message.from);
        const messageTime = new Date().toISOString();
        
        // Create a structured message object
        const newMessage = {
            id: new Date().getTime(), // Use timestamp as temporary ID
            senderId: message.from,
            senderName: senderName,
            senderAvatar: senderAvatar,
            textContent: message.content,
            createdAt: messageTime,
            messageType: 'TEXT'
        };
        
        // Store the message in history
        storeMessageInHistory(newMessage);
        
        // Play message received sound - always play for any message
        playMessageSound('received');
        
        // Check if this message is for the current chat
        if (currentChatUserId && message.from == currentChatUserId) {
            // Add the message to the current chat
            addMessageToChat(newMessage);
            
            // Scroll to the bottom of the chat
            scrollChatToBottom();
        } else {
            // If not in the current chat, show a notification
            showMessageNotification(newMessage);
        }
        
        // Update the contact sidebar for any message
        updateLastMessageInSidebar(message.from, message.content);
        
        // Increase unread count if not in current chat
        if (!currentChatUserId || message.from != currentChatUserId) {
            incrementUnreadCount(message.from);
        }
        
        // Update UI elements to reflect the new message
        updateUIAfterNewMessage(message.from);
    }
}

/**
 * Store message in history
 * @param {Object} message The message to store
 */
function storeMessageInHistory(message) {
    // Initialize history for this contact if it doesn't exist
    const contactId = message.senderId;
    if (!messageHistory[contactId]) {
        messageHistory[contactId] = [];
    }
    
    // Add message to history
    messageHistory[contactId].push(message);
    
    // Sort messages by time
    messageHistory[contactId].sort((a, b) => 
        new Date(a.createdAt) - new Date(b.createdAt)
    );
    
    console.log(`Message stored in history for contact ${contactId}. Total: ${messageHistory[contactId].length} messages`);
}

/**
 * Increment unread count for a contact
 */
function incrementUnreadCount(contactId) {
    // Find the contact
    const contact = messageContacts.find(c => c.id == contactId);
    if (!contact) return;
    
    // Increment unread count
    contact.unreadCount = (contact.unreadCount || 0) + 1;
    
    // Update UI
    const contactItem = document.querySelector(`.contact-item[data-id="${contactId}"]`);
    if (!contactItem) return;
    
    let badgeElement = contactItem.querySelector('.unread-badge');
    if (badgeElement) {
        badgeElement.textContent = contact.unreadCount;
    } else {
        badgeElement = document.createElement('div');
        badgeElement.className = 'unread-badge';
        badgeElement.textContent = contact.unreadCount;
        contactItem.appendChild(badgeElement);
    }
    
    // Move contact to top of list for new messages
    const parent = contactItem.parentNode;
    if (parent && parent.firstChild !== contactItem) {
        parent.removeChild(contactItem);
        parent.insertBefore(contactItem, parent.firstChild);
    }
}

/**
 * Get current user ID
 */
function getCurrentUserId() {
    if (currentUserId) {
        return currentUserId;
    }
    
    if (window.currentUserId) {
        return window.currentUserId;
    }
    
    // If both fail, return a default for testing
    console.warn('Using default user ID in messages.js');
    return 1;
}

/**
 * Load contacts for messaging
 * @returns {Promise} A promise that resolves when contacts are loaded
 */
function loadContactsForMessaging() {
    return new Promise((resolve, reject) => {
        // Show loading state
        const messageContactsContainer = document.getElementById('message-contacts');
        if (messageContactsContainer) {
            messageContactsContainer.innerHTML = `
                <div class="loading-spinner">
                    <i class="fas fa-spinner fa-spin"></i>
                    <span>加载联系人...</span>
                </div>
            `;
        }
        
        const currentUserId = getCurrentUserId();
        if (!currentUserId) {
            showMessagingError('无法获取当前用户ID，请重新登录');
            reject(new Error('Current user ID not available'));
            return;
        }
        
        // Fetch friends from backend
        const baseUrl = window.location.origin;
        fetch(`${baseUrl}/api/friendships/friends/${currentUserId}`, {
            credentials: 'include',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
        })
        .then(friends => {
            console.log('Loaded friends for messaging:', friends);
            
            // Map friends to contacts format and store in global variable
            messageContacts = friends.map(friend => ({
                id: friend.id,
                name: friend.fullName || friend.username,
                avatar: friend.avatarUrl || '/images/avatar.png',
                status: 'online', // Default status, could be updated with real status
                lastMessage: '',
                lastMessageTime: '',
                unreadCount: 0
            }));
            
            // Render contacts list
            renderMessageContacts(messageContacts);
            
            // Get unread message counts
            loadUnreadMessageCounts();
            
            // Load last messages for each contact
            loadLastMessages();
            
            resolve();
        })
        .catch(error => {
            console.error('Error loading friends for messaging:', error);
            showMessagingError('加载好友列表失败，请稍后再试');
            reject(error);
        });
    });
}

/**
 * Render the message contacts in the sidebar
 */
function renderMessageContacts(contacts) {
    const messageContactsContainer = document.getElementById('message-contacts');
    if (!messageContactsContainer) return;
    
    if (contacts.length === 0) {
        messageContactsContainer.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-user-friends"></i>
                <p>您还没有联系人，请先添加好友</p>
            </div>
        `;
        return;
    }
    
    messageContactsContainer.innerHTML = '';
    
    contacts.forEach(contact => {
        const contactItem = document.createElement('div');
        contactItem.className = 'contact-item';
        contactItem.setAttribute('data-id', contact.id);
        contactItem.setAttribute('data-favorite', contact.isFavorite ? 'true' : 'false');
        
        contactItem.innerHTML = `
            <div class="contact-avatar">
                <img src="${contact.avatar}" alt="${contact.name}">
                <span class="status-indicator status-${contact.status}"></span>
            </div>
            <div class="contact-info">
                <div class="contact-name">${contact.name}</div>
                <div class="contact-last-message">${contact.lastMessage || '暂无消息'}</div>
                <div class="contact-time">${contact.lastMessageTime || ''}</div>
            </div>
            ${contact.unreadCount > 0 ? `<div class="unread-badge">${contact.unreadCount}</div>` : ''}
        `;
        contactItem.addEventListener('click', function() {
            openChat(contact.id);
        });
        messageContactsContainer.appendChild(contactItem);
    });
}
function loadUnreadMessageCounts() {
    if (!messageContacts.length) return;
    const currentUserId = getCurrentUserId();
    if (!currentUserId) return;
    const baseUrl = window.location.origin;
    messageContacts.forEach(contact => {
        fetch(`${baseUrl}/api/messages/unread-count-in-room/${contact.id}`, {
            credentials: 'include'
        })
        .then(response => {
            if (!response.ok) {
                console.warn(`Could not get unread count for contact ${contact.id}`);
                return { count: 0 };
            }
            return response.json();
        })
        .then(data => {
            contact.unreadCount = data.count || 0;
            const contactItem = document.querySelector(`.contact-item[data-id="${contact.id}"]`);
            if (contactItem) {
                const badgeElement = contactItem.querySelector('.unread-badge');
                if (contact.unreadCount > 0) {
                    if (badgeElement) {
                        badgeElement.textContent = contact.unreadCount;
                    } else {
                        const badge = document.createElement('div');
                        badge.className = 'unread-badge';
                        badge.textContent = contact.unreadCount;
                        contactItem.appendChild(badge);
                    }
                } else if (badgeElement) {
                    badgeElement.remove();
                }
            }
        })
        .catch(error => {
            console.error(`Error getting unread count for contact ${contact.id}:`, error);
        });
    });
}
function loadLastMessages() {
    if (!messageContacts.length) return;
    const currentUserId = getCurrentUserId();
    if (!currentUserId) return;
    const baseUrl = window.location.origin;
    messageContacts.forEach(contact => {
        fetch(`${baseUrl}/api/messages/chat-with-user/${contact.id}/get-dto?page=0&size=1`, {
            credentials: 'include'
        })
        .then(response => {
            if (!response.ok) {
                return { messages: [] };
            }
            return response.json();
        })
        .then(data => {
            if (data.messages && data.messages.length > 0) {
                const lastMessage = data.messages[0];
                contact.lastMessage = getMessagePreview(lastMessage);
                contact.lastMessageTime = formatMessageTime(new Date(lastMessage.createdAt));
                const contactItem = document.querySelector(`.contact-item[data-id="${contact.id}"]`);
                if (contactItem) {
                    const lastMessageElement = contactItem.querySelector('.contact-last-message');
                    const timeElement = contactItem.querySelector('.contact-time');
                    if (lastMessageElement) {
                        lastMessageElement.textContent = contact.lastMessage;
                    }
                    if (timeElement) {
                        timeElement.textContent = contact.lastMessageTime;
                    }
                }
            }
        })
        .catch(error => {
            console.error(`Error getting last message for contact ${contact.id}:`, error);
        });
    });
}
function openChat(contactId) {
    document.getElementById('empty-chat').style.display = 'none';
    document.getElementById('chat-container').style.display = 'flex';
    currentChatUserId = contactId;
    const contact = messageContacts.find(c => c.id === contactId);
    if (contact) {
        updateChatHeader(contact);
        loadChatHistory(contactId);
        highlightSelectedContact(contactId);
        markMessagesAsRead(contactId);
        updateMessagesTabNotification();
    } else {
        console.error('Contact not found in loaded contacts');
        showChatError('无法加载联系人信息，请重试');
    }
}
function updateChatHeader(contact) {
    const chatContactName = document.getElementById('chat-contact-name');
    const chatContactAvatar = document.getElementById('chat-contact-avatar');
    const chatContactStatus = document.getElementById('chat-contact-status');
    if (chatContactName && contact) {
        chatContactName.textContent = contact.name || '未知联系人';
    }
    if (chatContactAvatar && contact) {
        chatContactAvatar.src = contact.avatar || '/images/avatar.png';
        chatContactAvatar.alt = contact.name || '联系人头像';
    }
    if (chatContactStatus && contact) {
        chatContactStatus.className = 'status';
        chatContactStatus.classList.add(contact.status || 'offline');
        const statusText = {
            'online': '在线',
            'offline': '离线',
            'busy': '忙碌'
        };
        chatContactStatus.textContent = statusText[contact.status] || '离线';
    }
    document.title = (contact && contact.name) ? `${contact.name} · 消息` : '消息';
}
function highlightSelectedContact(contactId) {
    const contactItems = document.querySelectorAll('.contact-item');
    contactItems.forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('data-id') == contactId) {
            item.classList.add('active');
        }
    });
}
function loadChatHistory(contactId) {
    const chatMessagesContainer = document.getElementById('chat-messages');
    if (!chatMessagesContainer) return;
    chatMessagesContainer.innerHTML = `
        <div class="loading-indicator">
            <i class="fas fa-spinner fa-spin"></i>
            <span>加载消息历史...</span>
        </div>
    `;
    const currentUserId = getCurrentUserId();
    if (!currentUserId) {
        showChatError('无法获取当前用户ID，请重新登录');
        return;
    }
    if (messageHistory[contactId] && messageHistory[contactId].length > 0) {
        console.log(`Using cached message history for contact ${contactId}. Found ${messageHistory[contactId].length} messages.`);
        renderChatHistory(messageHistory[contactId], currentUserId);
        markMessagesAsRead(contactId);
        return;
    }
    const baseUrl = window.location.origin;
    fetch(`${baseUrl}/api/messages/chat-with-user/${contactId}/read-and-get-dto?page=0&size=50`, {
        credentials: 'include'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (!data.messages || data.messages.length === 0) {
            chatMessagesContainer.innerHTML = `
            `;
            return;
        }
        data.messages.forEach(msg => {
            storeMessageInHistory(msg);
        });
        renderChatHistory(data.messages, currentUserId);
        markMessagesAsRead(contactId);
        chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
    })
    .catch(error => {
        console.error('Error loading chat history:', error);
        showChatError('加载消息历史失败，请稍后再试');
    });
}
function markMessagesAsRead(contactId) {
    const contact = messageContacts.find(c => c.id == contactId);
    if (contact) {
        contact.unreadCount = 0;
        const contactItem = document.querySelector(`.contact-item[data-id="${contactId}"]`);
        if (contactItem) {
            const badge = contactItem.querySelector('.unread-badge');
            if (badge) badge.remove();
        }
    }
}
function renderChatHistory(messages, currentUserId) {
    const chatMessagesContainer = document.getElementById('chat-messages');
    if (!chatMessagesContainer) return;
    chatMessagesContainer.innerHTML = '';
    const sortedMessages = messages.sort((a, b) =>
        new Date(a.createdAt) - new Date(b.createdAt)
    );
    let currentDate = null;
    sortedMessages.forEach(message => {
        const messageDate = new Date(message.createdAt);
        const messageDateStr = formatMessageDate(messageDate);
        if (messageDateStr !== currentDate) {
            currentDate = messageDateStr;
            const dateSeparator = document.createElement('div');
            dateSeparator.className = 'message-date-separator';
            dateSeparator.innerHTML = `<span>${currentDate}</span>`;
            chatMessagesContainer.appendChild(dateSeparator);
        }
        const messageElement = document.createElement('div');
        messageElement.className = `message ${message.senderId == currentUserId ? 'sent' : 'received'}`;
        messageElement.setAttribute('data-id', message.id);
        const senderName = message.senderName || getSenderName(message.senderId);
        const senderAvatar = message.senderAvatar || getSenderAvatar(message.senderId);
        let messageContent = '';
        if (message.isRecalled) {
            messageContent = '<div class="message-recalled">[消息已撤回]</div>';
        } else {
            switch (message.messageType) {
                case 'TEXT':
                    messageContent = `<div class="message-text">${message.textContent}</div>`;
                    break;
                case 'IMAGE':
                    messageContent = `
                        <div class="message-image">
                            <img src="${message.mediaUrl}" alt="Image">
                        </div>
                    `;
                    break;
                case 'VIDEO':
                    messageContent = `
                        <div class="message-video">
                            <video controls>
                                <source src="${message.mediaUrl}" type="video/mp4">
                                您的浏览器不支持视频播放
                            </video>
                        </div>
                    `;
                    break;
                case 'AUDIO':
                    messageContent = `
                        <div class="message-audio">
                            <audio controls>
                                <source src="${message.mediaUrl}" type="audio/mpeg">
                                您的浏览器不支持音频播放
                            </audio>
                            <span class="audio-duration">${formatAudioDuration(message.mediaDuration)}</span>
                        </div>
                    `;
                    break;
                case 'FILE':
                    messageContent = `
                        <div class="message-file">
                            <i class="fas fa-file"></i>
                            <a href="${message.mediaUrl}" target="_blank" download>下载文件</a>
                        </div>
                    `;
                    break;
                default:
                    messageContent = `<div class="message-text">${message.textContent || '[未知消息类型]'}</div>`;
            }
        }
        const avatarHtml = `
            <div class="message-avatar">
                <img src="${senderAvatar}" alt="${senderName}">
            </div>
        `;
        messageElement.innerHTML = `
            ${avatarHtml}
            <div class="message-content">
                ${message.senderId != currentUserId ? `<div class="message-sender">${senderName}</div>` : ''}
                ${message.replyToMessageId ? `
                    <div class="message-reply-to">
                        <div class="reply-preview">${message.replyToMessagePreview}</div>
                    </div>
                ` : ''}
                ${messageContent}
                <div class="message-time">
                    ${formatMessageTime(new Date(message.createdAt))}
                    ${message.isReadByCurrentUser ? '<i class="fas fa-check read-indicator"></i>' : ''}
                </div>
            </div>
            <div class="message-actions">
                <button class="btn-icon message-action" data-action="reply" title="回复">
                    <i class="fas fa-reply"></i>
                </button>
                ${message.senderId == currentUserId ? `
                    <button class="btn-icon message-action" data-action="recall" title="撤回">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                ` : ''}
            </div>
        `;
        chatMessagesContainer.appendChild(messageElement);
        const replyBtn = messageElement.querySelector('[data-action="reply"]');
        if (replyBtn) {
            replyBtn.addEventListener('click', () => {
                const preview = message.messageType === 'TEXT' 
                    ? message.textContent.substring(0, 30) + (message.textContent.length > 30 ? '...' : '')
                    : getMessagePreview(message);
                setupReply(message.id, preview);
            });
        }
        const recallBtn = messageElement.querySelector('[data-action="recall"]');
        if (recallBtn) {
            recallBtn.addEventListener('click', () => {
                if (confirm('确定要撤回此消息吗？')) {
                    console.log(`Recalling message: ${message.id}`);
                    messageElement.classList.add('recalled');
                    const contentEl = messageElement.querySelector('.message-content');
                    if (contentEl) {
                        contentEl.innerHTML = '<div class="message-recalled">[消息已撤回]</div>';
                    }
                }
            });
        }
    });
    scrollChatToBottom();
}
function getSenderAvatar(senderId) {
    const contact = messageContacts.find(c => c.id === senderId);
    if (contact && contact.avatar) {
        return contact.avatar;
    }
    return '/images/avatar.png';
}
function getSenderName(senderId) {
    const contact = messageContacts.find(c => c.id === senderId);
    return contact ? contact.name : `User ${senderId}`;
}
function scrollChatToBottom() {
    const chatMessagesContainer = document.getElementById('chat-messages');
    if (chatMessagesContainer) {
        chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
    }
}
function formatMessageDate(date) {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.toDateString() === today.toDateString()) {
        return '今天';
    } else if (date.toDateString() === yesterday.toDateString()) {
        return '昨天';
    } else {
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
    }
}
function formatMessageTime(date) {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const timeStr = `${hours}:${minutes}`;
    if (date.toDateString() === today.toDateString()) {
        return timeStr;
    } else if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 ${timeStr}`;
    } else {
        return `${date.getMonth() + 1}月${date.getDate()}日 ${timeStr}`;
    }
}
function formatAudioDuration(seconds) {
    if (!seconds) return '00:00';
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
}
function getMessagePreview(message) {
    if (!message) return '';
    
    if (message.isRecalled) {
        return '[消息已撤回]';
    }
    switch (message.messageType) {
        case 'TEXT':
            const text = message.textContent || '';
            if (text.length > 15) {
                return text.substring(0, 15) + '...';
            }
            return text;
        case 'IMAGE':
            return '[图片]';
        case 'VIDEO':
            return '[视频]';
        case 'AUDIO':
            return '[语音]';
        case 'FILE':
            return '[文件]';
        default:
            return '[消息]';
    }
}
function showChatError(message) {
    const chatMessagesContainer = document.getElementById('chat-messages');
    if (chatMessagesContainer) {
        chatMessagesContainer.innerHTML = `
            <div class="error-state">
                <i class="fas fa-exclamation-circle"></i>
                <p>${message}</p>
                <button class="btn btn-primary retry-btn" onclick="loadChatHistory(currentChatUserId)">重试</button>
            </div>
        `;
    }
}
function showMessagingError(message) {
    const messageContactsContainer = document.getElementById('message-contacts');
    if (messageContactsContainer) {
        messageContactsContainer.innerHTML = `
            <div class="error-state">
                <i class="fas fa-exclamation-circle"></i>
                <p>${message}</p>
                <button class="btn btn-primary retry-btn" onclick="loadContactsForMessaging()">重试</button>
            </div>
        `;
    }
}
function initializeMessageTabs() {
    const tabs = document.querySelectorAll('.message-tabs .tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            const tabType = this.getAttribute('data-tab');
            filterMessagesByTab(tabType);
        });
    });
}
function filterMessagesByTab(tabType) {
    const contactItems = document.querySelectorAll('.contact-item');
    contactItems.forEach(item => {
        if (tabType === 'recent') {
            item.style.display = 'flex';
        } else if (tabType === 'unread') {
            const unreadBadge = item.querySelector('.unread-badge');
            item.style.display = unreadBadge && parseInt(unreadBadge.textContent) > 0 ? 'flex' : 'none';
        } else if (tabType === 'favorite') {
            const isFavorite = item.getAttribute('data-favorite') === 'true';
            item.style.display = isFavorite ? 'flex' : 'none';
        }
    });
}
function initializeNewMessageButton() {
    const messageTabs = document.querySelector('.message-tabs');
    if (messageTabs) {
        const newButton = document.createElement('button');
        newButton.className = 'btn-icon new-msg-btn';
        newButton.innerHTML = '<i class="fas fa-edit"></i>';
        newButton.title = '新建消息';
        messageTabs.appendChild(newButton);
        newButton.addEventListener('click', function() {
            showNewMessageModal();
        });
    }
    const startNewMessageBtn = document.getElementById('start-new-message');
    if (startNewMessageBtn) {
        startNewMessageBtn.addEventListener('click', function() {
            showNewMessageModal();
        });
    }
}
function showNewMessageModal() {
    const modal = document.getElementById('new-message-modal');
    if (modal) {
        modal.style.display = 'flex';
        const closeButton = document.getElementById('close-message-modal');
        if (closeButton) {
            closeButton.addEventListener('click', function() {
                modal.style.display = 'none';
            });
        }
        loadContactsForNewMessage();
    }
}
function loadContactsForNewMessage() {
    console.log('Loading contacts for new message modal');
}
function initializeSendMessage() {
    const sendButton = document.getElementById('send-message-btn');
    const messageInput = document.getElementById('message-input');
    if (sendButton && messageInput) {
        sendButton.addEventListener('click', function() {
            sendTextMessage();
        });
        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault(); // Prevent default to avoid newline
                sendTextMessage();
            }
        });
    }
}
function sendTextMessage() {
    if (!currentChatUserId) {
        console.error('No chat is currently open');
        return;
    }
    const messageInput = document.getElementById('message-input');
    if (!messageInput) return;
    const textContent = messageInput.value.trim();
    if (!textContent) return; // Don't send empty messages
    const currentUserId = getCurrentUserId();
    if (!currentUserId) {
        showChatError('无法获取当前用户ID，请重新登录');
        return;
    }
    messageInput.value = '';
    const messageId = `msg_${Date.now()}`;
    const newMessage = {
        id: messageId,
        senderId: currentUserId,
        senderName: 'Me', // Current user
        senderAvatar: getCurrentUserAvatar(),
        textContent: textContent,
        createdAt: new Date().toISOString(),
        messageType: 'TEXT',
        replyToMessageId: replyToMessageId,
        replyToMessagePreview: replyToMessageId ? 
            document.querySelector('.reply-preview-text')?.textContent : null,
        isSending: true // Mark as sending initially
    };
    storeMessageInHistory(newMessage);
    addMessageToChatUI(newMessage);
    playMessageSound('sent');
    if (replyToMessageId) {
        cancelReply();
    }
    if (window.wsClient && window.wsClient.isConnected()) {
        window.wsClient.sendTextMessage(currentChatUserId, textContent);
        setTimeout(() => {
            updateMessageStatus(messageId, 'sent');
        }, 500);
    } else {
        console.error('WebSocket is not connected');
        updateMessageStatus(messageId, 'failed');
    }
}
function addMessageToChatUI(message) {
    const chatMessagesContainer = document.getElementById('chat-messages');
    if (!chatMessagesContainer) return;
    const messageDate = new Date(message.createdAt);
    const messageDateStr = formatMessageDate(messageDate);
    const dateSeparators = chatMessagesContainer.querySelectorAll('.message-date-separator');
    const lastDateSeparator = dateSeparators.length > 0 ? dateSeparators[dateSeparators.length - 1] : null;
    if (!lastDateSeparator || lastDateSeparator.querySelector('span').textContent.trim() !== messageDateStr) {
        const dateSeparator = document.createElement('div');
        dateSeparator.className = 'message-date-separator';
        dateSeparator.innerHTML = `<span>${messageDateStr}</span>`;
        chatMessagesContainer.appendChild(dateSeparator);
    }
    const currentUserId = getCurrentUserId();
    const messageElement = document.createElement('div');
    messageElement.className = `message ${message.senderId == currentUserId ? 'sent' : 'received'}`;
    if (message.isSending) {
        messageElement.classList.add('sending');
    } else if (message.isFailed) {
        messageElement.classList.add('failed');
    }
    messageElement.setAttribute('data-id', message.id);
    const avatarHtml = `
        <div class="message-avatar">
            <img src="${message.senderAvatar || getSenderAvatar(message.senderId)}" alt="${message.senderName}">
        </div>
    `;
    let messageContent = '';
    if (message.isRecalled) {
        messageContent = '<div class="message-recalled">[消息已撤回]</div>';
    } else {
        // Handle different message types
        switch (message.messageType) {
            case 'TEXT':
                messageContent = `<div class="message-text">${message.textContent}</div>`;
                break;
            case 'IMAGE':
                messageContent = `
                    <div class="message-image">
                        <img src="${message.mediaUrl}" alt="Image">
                    </div>
                `;
                break;
            case 'VIDEO':
                messageContent = `
                    <div class="message-video">
                        <video controls>
                            <source src="${message.mediaUrl}" type="video/mp4">
                            您的浏览器不支持视频播放
                        </video>
                    </div>
                `;
                break;
            case 'AUDIO':
                messageContent = `
                    <div class="message-audio">
                        <audio controls>
                            <source src="${message.mediaUrl}" type="audio/mpeg">
                            您的浏览器不支持音频播放
                        </audio>
                        <span class="audio-duration">${formatAudioDuration(message.mediaDuration)}</span>
                    </div>
                `;
                break;
            case 'FILE':
                messageContent = `
                    <div class="message-file">
                        <i class="fas fa-file"></i>
                        <a href="${message.mediaUrl}" target="_blank" download>下载文件</a>
                    </div>
                `;
                break;
            default:
                messageContent = `<div class="message-text">${message.textContent || '[未知消息类型]'}</div>`;
        }
    }
    let statusIcon = '';
    if (message.senderId == currentUserId) {
        if (message.isSending) {
            statusIcon = '<i class="fas fa-clock sending-indicator"></i>';
        } else if (message.isFailed) {
            statusIcon = '<i class="fas fa-exclamation-circle error-indicator"></i>';
        } else if (message.isRead) {
            statusIcon = '<i class="fas fa-check-double read-indicator"></i>';
        } else {
            statusIcon = '<i class="fas fa-check sent-indicator"></i>';
        }
    }
    messageElement.innerHTML = `
        ${avatarHtml}
        <div class="message-content">
            ${message.senderId != currentUserId ? `<div class="message-sender">${message.senderName}</div>` : ''}
            ${message.replyToMessageId ? `
                <div class="message-reply-to">
                    <div class="reply-preview">${message.replyToMessagePreview}</div>
                </div>
            ` : ''}
            ${messageContent}
            <div class="message-time">
                ${formatMessageTime(messageDate)}
                ${statusIcon}
            </div>
        </div>
        <div class="message-actions">
            <button class="btn-icon message-action" data-action="reply" title="回复">
                <i class="fas fa-reply"></i>
            </button>
            ${message.senderId == currentUserId ? `
                <button class="btn-icon message-action" data-action="recall" title="撤回">
                    <i class="fas fa-trash-alt"></i>
                </button>
            ` : ''}
            ${message.isFailed ? `
                <button class="btn-icon message-action retry-btn" data-action="retry" title="重试">
                    <i class="fas fa-redo"></i>
                </button>
            ` : ''}
        </div>
    `;
    chatMessagesContainer.appendChild(messageElement);
    const replyBtn = messageElement.querySelector('[data-action="reply"]');
    if (replyBtn) {
        replyBtn.addEventListener('click', () => {
            const preview = message.textContent && message.textContent.substring(0, 30) + 
                (message.textContent.length > 30 ? '...' : '');
            setupReply(message.id, preview || getMessagePreview(message));
        });
    }
    const recallBtn = messageElement.querySelector('[data-action="recall"]');
    if (recallBtn) {
        recallBtn.addEventListener('click', () => {
            if (confirm('确定要撤回此消息吗？')) {
                recallMessage(message.id);
            }
        });
    }
    const retryBtn = messageElement.querySelector('[data-action="retry"]');
    if (retryBtn) {
        retryBtn.addEventListener('click', () => {
            retryMessage(message.id);
        });
    }
    scrollChatToBottom();
}
function addMessageToChat(message) {
    addMessageToChatUI(message);
}
function updateMessageStatus(messageId, status) {
    const messageElement = document.querySelector(`.message[data-id="${messageId}"]`);
    if (!messageElement) return;
    messageElement.classList.remove('sending', 'failed');
    if (status === 'failed') {
        messageElement.classList.add('failed');
    }
    const timeElement = messageElement.querySelector('.message-time');
    if (timeElement) {
        const icon = timeElement.querySelector('i');
        if (icon) {
            icon.className = status === 'sent' 
                ? 'fas fa-check sent-indicator' 
                : 'fas fa-exclamation-circle error-indicator';
        }
    }
    if (status === 'failed') {
        const actionsContainer = messageElement.querySelector('.message-actions');
        if (actionsContainer && !actionsContainer.querySelector('[data-action="retry"]')) {
            const retryBtn = document.createElement('button');
            retryBtn.className = 'btn-icon message-action retry-btn';
            retryBtn.setAttribute('data-action', 'retry');
            retryBtn.setAttribute('title', '重试');
            retryBtn.innerHTML = '<i class="fas fa-redo"></i>';
            retryBtn.addEventListener('click', () => {
                retryMessage(messageId);
            });
            actionsContainer.appendChild(retryBtn);
        }
    }
    updateMessageInHistory(messageId, { isSending: false, isFailed: status === 'failed' });
}
function updateMessageInHistory(messageId, updates) {
    // Scan all contact messages to find the message
    Object.keys(messageHistory).forEach(contactId => {
        const messages = messageHistory[contactId];
        const messageIndex = messages.findIndex(m => m.id === messageId);
        if (messageIndex !== -1) {
            messageHistory[contactId][messageIndex] = {
                ...messageHistory[contactId][messageIndex],
                ...updates
            };
        }
    });
}
function recallMessage(messageId) {
    const messageElement = document.querySelector(`.message[data-id="${messageId}"]`);
    if (!messageElement) return;
    const contentElement = messageElement.querySelector('.message-content');
    if (contentElement) {
        const messageTextElement = contentElement.querySelector('.message-text');
        if (messageTextElement) {
            messageTextElement.innerHTML = '<div class="message-recalled">[消息已撤回]</div>';
        }
    }
    updateMessageInHistory(messageId, { isRecalled: true });
    console.log(`Message ${messageId} recalled`);
}
function retryMessage(messageId) {
    let foundMessage = null;
    let contactId = null;
    Object.keys(messageHistory).forEach(cId => {
        const messages = messageHistory[cId];
        const message = messages.find(m => m.id === messageId);
        if (message) {
            foundMessage = message;
            contactId = cId;
        }
    });
    if (!foundMessage || !contactId) {
        console.error(`Message ${messageId} not found for retry`);
        return;
    }
    updateMessageStatus(messageId, 'sending');
    const messageElement = document.querySelector(`.message[data-id="${messageId}"]`);
    if (messageElement) {
        messageElement.classList.remove('failed');
        messageElement.classList.add('sending');
    }
    if (window.wsClient && window.wsClient.isConnected()) {
        window.wsClient.sendTextMessage(contactId, foundMessage.textContent);
        setTimeout(() => {
            updateMessageStatus(messageId, 'sent');
        }, 500);
    } else {
        setTimeout(() => {
            updateMessageStatus(messageId, 'failed');
        }, 500);
    }
}
function playMessageSound(type) {
    if (typeof Audio !== 'undefined') {
        try {
            const soundUrl = type === 'sent' 
                ? '/sounds/message-sent.mp3' 
                : '/sounds/message-received.mp3';
            const sound = new Audio(soundUrl);
            sound.volume = 0.3;
            sound.play().catch(e => {
                console.log('Could not play notification sound:', e);
            });
        } catch (error) {
            console.log('Sound playback error (safely handled):', error);
        }
    }
}
function addOptimisticMessage(textContent) {
    const chatMessagesContainer = document.getElementById('chat-messages');
    if (!chatMessagesContainer) return;
    const messageElement = document.createElement('div');
    messageElement.className = 'message sent optimistic';
    const now = new Date();
    const timeStr = formatMessageTime(now);
    const currentUserAvatar = getCurrentUserAvatar();
    let replyContent = '';
    if (replyToMessageId) {
        const replyPreview = document.querySelector('.reply-preview-text');
        if (replyPreview) {
            replyContent = `
                <div class="message-reply-to">
                    <div class="reply-preview">${replyPreview.textContent}</div>
                </div>
            `;
        }
    }
    messageElement.innerHTML = `
        <div class="message-avatar">
            <img src="${currentUserAvatar}" alt="Me">
        </div>
        <div class="message-content">
            ${replyContent}
            <div class="message-text">${textContent}</div>
            <div class="message-time">
                ${timeStr}
                <i class="fas fa-clock sending-indicator"></i>
            </div>
        </div>
    `;
    chatMessagesContainer.appendChild(messageElement);
    scrollChatToBottom();
}
function getCurrentUserAvatar() {
    // Try to find user info in the header
    const headerAvatar = document.querySelector('.user-info .avatar');
    if (headerAvatar && headerAvatar.src) {
        return headerAvatar.src;
    }
    return '/images/avatar.png';
}
function updateLastMessageInSidebar(contactId, lastMessage) {
    // Find the contact in our data
    const contact = messageContacts.find(c => c.id === contactId);
    if (contact) {
        contact.lastMessage = lastMessage.length > 15 ? lastMessage.substring(0, 15) + '...' : lastMessage;
        contact.lastMessageTime = formatMessageTime(new Date());
        const contactItem = document.querySelector(`.contact-item[data-id="${contactId}"]`);
        if (contactItem) {
            const lastMessageElement = contactItem.querySelector('.contact-last-message');
            const timeElement = contactItem.querySelector('.contact-time');
            if (lastMessageElement) {
                lastMessageElement.textContent = contact.lastMessage;
            }
            if (timeElement) {
                timeElement.textContent = contact.lastMessageTime;
            }
            const parent = contactItem.parentNode;
            if (parent && parent.firstChild !== contactItem) {
                parent.removeChild(contactItem);
                parent.insertBefore(contactItem, parent.firstChild);
            }
        }
    }
}
function showSendMessageError() {
    // Find the optimistic message and mark it as failed
    const optimisticMessage = document.querySelector('.message.optimistic');
    if (optimisticMessage) {
        optimisticMessage.classList.add('failed');
        const timeElement = optimisticMessage.querySelector('.message-time');
        if (timeElement) {
            timeElement.innerHTML = `
                <span class="error-text">发送失败</span>
                <button class="btn-text retry-send">重试</button>
            `;
            const retryButton = optimisticMessage.querySelector('.retry-send');
            if (retryButton) {
                retryButton.addEventListener('click', function() {
                    // Remove the failed message and retry sending
                    optimisticMessage.remove();
                    sendTextMessage();
                });
            }
        }
    }
}
function setupReply(messageId, messagePreview) {
    replyToMessageId = messageId;
    let replyArea = document.querySelector('.reply-area');
    if (!replyArea) {
        replyArea = document.createElement('div');
        replyArea.className = 'reply-area';
        replyArea.innerHTML = `
            <div class="reply-preview-container">
                <div class="reply-preview-label">回复:</div>
                <div class="reply-preview-text"></div>
            </div>
            <button class="btn-icon cancel-reply">
                <i class="fas fa-times"></i>
            </button>
        `;
        replyArea.querySelector('.cancel-reply').addEventListener('click', cancelReply);
        const chatInputArea = document.querySelector('.chat-input-area');
        chatInputArea.insertBefore(replyArea, chatInputArea.firstChild);
    }
    const previewText = replyArea.querySelector('.reply-preview-text');
    if (previewText) {
        previewText.textContent = messagePreview;
    }
    document.getElementById('message-input').focus();
}
function cancelReply() {
    replyToMessageId = null;
    const replyArea = document.querySelector('.reply-area');
    if (replyArea) {
        replyArea.remove();
    }
}
window.sendMessageFromContacts = function(contactId) {
    console.log('Received request to open chat with contact ID:', contactId);
    document.getElementById('empty-chat').style.display = 'none';
    document.getElementById('chat-container').style.display = 'flex';
    currentChatUserId = typeof contactId === 'string' ? parseInt(contactId) : contactId;
    loadContactsForMessaging().then(() => {
        const contact = messageContacts.find(c => c.id === currentChatUserId);
        if (contact) {
            updateChatHeader(contact);
            loadChatHistory(currentChatUserId);
            highlightSelectedContact(currentChatUserId);
        } else {
            console.error('Contact not found in loaded contacts');
            showChatError('无法加载联系人信息，请重试');
        }
    });
};
function showMessageNotification(message) {
    const contact = messageContacts.find(c => c.id == message.senderId);
    if (!contact) return;
    if ('Notification' in window) {
        if (Notification.permission === 'granted') {
            createMessageNotification(contact, message);
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    createMessageNotification(contact, message);
                }
            });
        }
    }
    const messagesNavItem = document.querySelector('.nav-item[data-page="messages"]');
    if (messagesNavItem) {
        let notificationDot = messagesNavItem.querySelector('.notification-dot');
        if (!notificationDot) {
            notificationDot = document.createElement('div');
            notificationDot.className = 'notification-dot';
            messagesNavItem.appendChild(notificationDot);
        }
    }
}
function createMessageNotification(contact, message) {
    const notification = new Notification(`新消息来自 ${contact.name}`, {
        body: message.textContent.substring(0, 50) + (message.textContent.length > 50 ? '...' : ''),
        icon: contact.avatar || '/images/avatar.png'
    });
    notification.onclick = function() {
        window.focus();
        openChat(contact.id);
        notification.close();
    };
    setTimeout(() => {
        notification.close();
    }, 5000);
}
function updateUIAfterNewMessage(contactId) {
    if (currentChatUserId && contactId == currentChatUserId) {
        addChatHeaderInfo(contactId);
    }
    const contactItem = document.querySelector(`.contact-item[data-id="${contactId}"]`);
    if (contactItem) {
        contactItem.classList.add('new-message');
        setTimeout(() => {
            contactItem.classList.remove('new-message');
        }, 2000);
        const parent = contactItem.parentNode;
        if (parent && parent.firstChild !== contactItem) {
            parent.removeChild(contactItem);
            parent.insertBefore(contactItem, parent.firstChild);
        }
    }
}
function updateMessagesTabNotification() {
    const hasUnread = messageContacts.some(contact => contact.unreadCount > 0);
    const messagesNavItem = document.querySelector('.nav-item[data-page="messages"]');
    if (!messagesNavItem) return;
    let notificationDot = messagesNavItem.querySelector('.notification-dot');
    if (hasUnread) {
        if (!notificationDot) {
            notificationDot = document.createElement('div');
            notificationDot.className = 'notification-dot';
            messagesNavItem.appendChild(notificationDot);
        }
    } else if (notificationDot) {
        notificationDot.remove();
    }
}
function setupMessageInput() {
    const messageInput = document.getElementById('message-input');
    if (messageInput) {
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            const newHeight = Math.min(this.scrollHeight, 120);
            this.style.height = newHeight + 'px';
        });
        setTimeout(() => {
            messageInput.style.height = 'auto';
            messageInput.style.height = (messageInput.scrollHeight) + 'px';
        }, 0);
    }
}
